<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="card-box">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-upload
              :action="uploadFileUrl"
              :before-upload="handleBeforeUpload"
              :on-error="handleUploadError"
              :on-success="handleUploadSuccess"
              :show-file-list="false"
              :headers="headers"
              class="upload-file-uploader"
              ref="upload"
            >
              <!-- 上传按钮 -->
              <el-button icon="el-icon-upload" size="mini" type="primary">上传</el-button>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-folder-add"
              size="mini"
              @click="createFolder"
              v-hasPermi="['system:post:edit']"
            >新建</el-button>
          </el-col>
          <!--<el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:post:remove']"
            >删除</el-button>
          </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-card>
          <div slot="header">
            <span>当前目录</span>
            <div>
              <span v-if="path != ''"><a href="#" @click="previousLevel">返回上一级</a> | </span>
              <span>
                <a v-if="path != ''" href="#" @click="toRoot">全部文件 </a>
                <span v-if="path == ''" href="#" @click="toRoot">全部文件 </span>
              </span>
              <span v-for="(item, index) in path.split('/')">
                <span class="KLxwHFb"> > </span>
                <a v-if="index + 1 < path.split('/').length" href="#" @click="toPath(index)">{{ item }}</a>
                <span v-else>{{ item }}</span>
              </span>
            </div>
          </div>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" style="width: 100%;">
              <thead>
                <tr>
                  <th class="el-table__cell el-table__cell is-leaf"><div class="cell">文件名称</div></th>
                  <th class="el-table__cell is-leaf"><div class="cell">文件大小</div></th>
                  <th class="el-table__cell is-leaf"><div class="cell">修改日期</div></th>
                  <th class="el-table__cell is-leaf"><div class="cell">上传用户</div></th>
                  <th class="el-table__cell is-leaf"><div class="cell">操作</div></th>
                </tr>
              </thead>
              <tr v-for="(file, index) in fileList" :key="index">
                <td class="el-table__cell is-leaf">
                  <div class="cell">
                    <a v-if="file.directory" href="#" @click="openFolder(file.name)">{{ file.name }}</a>
                    <span v-else>{{ file.name }}</span>
                  </div>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ file.size }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ file.updateTime }}</div></td>
                <td class="el-table__cell is-leaf"><div class="cell">{{ file.uploaderName }}</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">
                    <a href="#" @click="downloadFile(file)">下载</a>
                    <span v-if="file.deletePerm" style="margin-left: 2px; margin-right: 2px;"> | </span>
                    <a v-if="file.deletePerm" href="#" @click="handleDelete(file.path)">删除</a>
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style>
 a {
   color: #09AAFF;
 }
 .KLxwHFb {
   color: #c5d8f3;
 }
</style>

<script>
import { fileList, createFolder, deleteFile } from "@/api/file/manage";
import { download } from '@/utils/request';
import { getToken } from '@/utils/auth'

export default {
  name: "fileManage",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      path: "",
      fileList: [],
      baseUploadUrl: process.env.VUE_APP_BASE_API + "/system/file/upload",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/file/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.openLoading();
      fileList(this.path).then(response => {
        this.fileList = response.data;
        this.$modal.closeLoading();
      });
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载文件目录数据，请稍候！");
    },
    // 返回上一级
    previousLevel() {
      this.path = this.path.substring(0, this.path.lastIndexOf("/"))
      this.getList()
    },
    // 返回根目录
    toRoot() {
      this.path = ""
      this.getList()
    },
    toPath(index) {
      this.path = this.path.substring(0, this.path.indexOf("/", index))
      this.getList()
    },
    openFolder(name) {
      this.path = this.path + "/" + name
      this.getList()
    },
    downloadFile(file) {
      download('/system/file/download', {filePath : file.path}, file.directory ? file.name + ".zip" : file.name)
    },

    // 上传前校检
    async handleBeforeUpload(file) {
      for(let index in this.fileList) {
        let item = this.fileList[index];
        await this.checkRepeatFile(file, item).then(res => {
          console.log(res)
        }).catch(err => {
          console.log(err)
        })
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.uploadFileUrl = this.baseUploadUrl + this.path
      return true;
    },
    // 校验是否已有原来的文件&是否可以上传覆盖
    async checkRepeatFile(file, item){
      let that = this
      return new Promise(function(resolve, reject) {
        if (file.name == item.name) {
          if (item.deletePerm) {
            that.$confirm('目录内已存在同名文件, 是否覆盖?', '提示', {
              confirmButtonText: '覆盖',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              resolve(true);
            }).catch(() => {
              that.$message({
                type: 'info',
                message: '已取消上传'
              });
              resolve(false);
            });
          } else {
            that.$message.error(`目录内已存在同名文件, 请修改上传文件名称`);
          }
        }
        resolve(true);
      });
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      this.fileList.push({ name: res.fileName, url: res.fileName });
      this.$emit("input", this.listToString(this.fileList));
    },
    // 删除文件
    handleDelete(index) {
      let file = this.fileList[index];
      this.$confirm('确认删除' + file.name + '?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFile(file.path).then(res => {
          this.getList();
          if (res.code === 200) {
            this.$modal.msgSuccess(res.msg);
            this.fileList.splice(index, 1);
            this.$emit("input", this.listToString(this.fileList));
          }else if(res.code == 409){
            this.forceDelete(file);
          }else{
            this.$modal.msgError(res.msg);
          }
        }).catch(() => {});
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    forceDelete(file){
      this.$confirm('确认删除' + file.name + '?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        forceDelete(file.path).then(res => {
          this.getList();
          if (res.code === 200) {
            this.$modal.msgSuccess(res.msg);
            this.fileList.splice(index, 1);
            this.$emit("input", this.listToString(this.fileList));
          }else{
            this.$modal.msgError(res.msg);
          }
        }).catch(() => {});
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 创建文件夹
    createFolder(){
      this.$prompt('请输入文件夹名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[^\\/:\*\?""<>|]/,
        inputErrorMessage: '文件夹名称格式不正确'
      }).then(({ value }) => {
        createFolder(this.path  + "/" +  value).then(response => {
          this.$message({
            type: 'success',
            message: '已创建: ' + value
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消新建'
        });
      });
    }
  }
};
</script>
